<template>
  <el-row :gutter="20">
    <el-col :span="12">
      <el-upload class="text-left" action="#" :http-request="beforeAvatarUpload" :show-file-list="false" accept=".xlsx,.xls">
          <el-button type="primary" :icon="UploadFilled">选择文件</el-button>
      </el-upload>
      <p><el-link type="primary" href="https://huajing-1344106420.cos.ap-shanghai.myqcloud.com/ContractDetails.xlsx">下载模板</el-link></p>
      <el-text>文件格式为（xlsx，xls）大小10M以内,重新上传则会替换原来的文件</el-text>
    </el-col>
    <el-col :span="12">
      <div class="text-right"><el-button type="success" @click="saveUploadExcel">确认导入</el-button></div>
    </el-col>
  </el-row>
  
  <el-divider border-style="dashed" />
  <el-table class="mt20" :data="tableData" border v-loading="form.loading" style="width: 100%;font-size: 16px;">
      <el-table-column type="index" :index="indexMethod" label="序号" width="60" />
      <el-table-column prop="name" label="项目名称" show-overflow-tooltip />
      <el-table-column prop="content" label="施工内容" />
      <el-table-column prop="unit" label="单位" />
      <el-table-column prop="work_quantity" label="数量" width="110"/>
      <el-table-column prop="unit_price" label="材料单价" width="110"/>
      <el-table-column prop="price" label="合价" width="110"/>
      <el-table-column prop="remarks" label="备注" width="110"/>
  </el-table>
</template>

<script lang="ts" setup>
import { ref,onMounted,watch  } from 'vue';
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus';
import * as XLSX from 'xlsx';
const indexMethod = (index: number) => {
  return index+= 1
}

interface schedule {
    id: number
    name:string
    content:string
    unit:string
    work_quantity:number
    price:number | string
    unit_price:number
    remarks:string
}

const tableData = ref<schedule[]>([])
const data = ref<string>()
const form = ref<any>({search:'',loading:false,parentBorder:false})
const props = defineProps<{
  data:any
}>()

watch(props,()=>{
  data.value = props.data
},{ immediate: true })

const beforeAvatarUpload = (rawFile:any) => {
  let file:any = rawFile.file
  const extension = file.name.split('.')[1] === 'xls'
	const extension2 = file.name.split('.')[1] === 'xlsx'
  if (file.size / 1024 / 1024 > 10) {
      ElMessage.error('文件不得大于10MB!')
      return false
  }

  if (!extension && !extension2) {
    ElMessage.error('上传模板只能是 xls、xlsx格式!')
	}
  form.value.loading = true
  const reader = new FileReader();
  reader.onload = (e:any) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array',cellDates: true });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    tableData.value = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    tableData.value = mapXLSX(tableData.value)
    form.value.loading = false
  };
  reader.readAsArrayBuffer(file);
  
}

const mapXLSX = (data:any) => {
    let arr:any = []
    data.forEach((e:any,i:number) => {
        if(i > 0){
            if(e[0]){
              e[0] = e[0] ? e[0] : ''
              e[1] = e[1] ? e[1] : ''
              e[2] = e[2] ? e[2] : ''
              e[3] = e[3] ? e[3] : 1
              e[4] = e[4] ? e[4] : 1
              e[5] = e[5] ? e[5] : ''
              let price = parseInt(e[3]) * parseInt(e[4]);
              arr.push({name:e[0],content:e[1],unit:e[2],work_quantity:parseInt(e[3]),unit_price:parseInt(e[4]),price:price,remarks:e[5]})
            }
        }
    });
    return arr
}
const saveUploadExcel = () => {
  emit('saveUploadExcel',tableData.value)
}

const emit = defineEmits(['saveUploadExcel'])

onMounted(()=>{

})
</script>
<style scoped>
</style>
